using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using Lzfy_His_Service.Models;
using Lzfy_His_Service.Services;
using System.Security.Claims;

namespace Lzfy_His_Service.Controllers
{
    /// <summary>
    /// 坐席账号管理控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    [Authorize]
    public class AgentAccountController : ControllerBase
    {
        private readonly IAgentAccountService _agentAccountService;
        private readonly ILogger<AgentAccountController> _logger;

        public AgentAccountController(
            IAgentAccountService agentAccountService,
            ILogger<AgentAccountController> logger)
        {
            _agentAccountService = agentAccountService;
            _logger = logger;
        }

        /// <summary>
        /// 申请坐席账号使用权
        /// </summary>
        /// <param name="request">申请请求</param>
        /// <returns>申请结果</returns>
        [HttpPost("apply")]
        public async Task<IActionResult> ApplyAccount([FromBody] AgentAccountApplyRequest request)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }

                var result = await _agentAccountService.ApplyAccountAsync(request);
                
                if (result == null)
                {
                    return Ok(new
                    {
                        success = false,
                        message = "当前没有可用的坐席账号，请稍后再试",
                        data = (object?)null
                    });
                }
                
                // 检查是否是用户已申请的情况
                if (result.Id == -1 && string.Equals(result.ApiUrl, "USER_ALREADY_APPLIED", StringComparison.Ordinal))
                {
                    return Ok(new
                    {
                        success = false,
                        message = "您已申请了坐席，请勿重复申请",
                        data = (object?)null
                    });
                }

                // 检查是否清理了不活跃账号后重新申请
                string message = "成功申请到坐席账号";
                if (result.ApiUrl?.StartsWith("CLEANED_INACTIVE:") == true)
                {
                    // 恢复原始ApiUrl
                    result.ApiUrl = result.ApiUrl.Substring("CLEANED_INACTIVE:".Length);
                    message = "您之前的坐席账号因长时间未使用已失效，已为您重新分配新的坐席账号";
                }

                return Ok(new
                {
                    success = true,
                    message = message,
                    data = result
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "申请坐席账号时发生错误: {Username}", request.Username);
                return StatusCode(500, new
                {
                    success = false,
                    message = "申请坐席账号时发生内部错误",
                    data = (object?)null
                });
            }
        }

        /// <summary>
        /// 确认或取消确认坐席账号使用权
        /// </summary>
        /// <param name="request">确认请求</param>
        /// <returns>操作结果</returns>
        [HttpPost("confirm")]
        public async Task<IActionResult> ConfirmAccount([FromBody] AgentAccountConfirmRequest request)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }

                var result = await _agentAccountService.ConfirmAccountAsync(request);
                
                if (result)
                {
                    var message = request.IsConfirm ? "成功确认坐席账号使用权" : "成功取消坐席账号使用权";
                    return Ok(new
                    {
                        success = true,
                        message = message,
                        data = (object?)null
                    });
                }
                else
                {
                    return Ok(new
                    {
                        success = false,
                        message = "操作失败，请检查账号状态",
                        data = (object?)null
                    });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "确认坐席账号时发生错误: {Username}, AccountId: {AccountId}", 
                    request.Username, request.AccountId);
                return StatusCode(500, new
                {
                    success = false,
                    message = "确认坐席账号时发生内部错误",
                    data = (object?)null
                });
            }
        }

        /// <summary>
        /// 记录用户操作时间
        /// </summary>
        /// <param name="request">操作记录请求</param>
        /// <returns>操作结果</returns>
        [HttpPost("record-action")]
        public async Task<IActionResult> RecordAction([FromBody] AgentAccountActionRequest request)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }

                var result = await _agentAccountService.RecordActionAsync(request);
                
                if (result)
                {
                    return Ok(new
                    {
                        success = true,
                        message = "成功记录操作时间",
                        data = (object?)null
                    });
                }
                else
                {
                    return Ok(new
                    {
                        success = false,
                        message = "记录操作时间失败，可能账号已过期或用户不匹配",
                        data = (object?)null
                    });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "记录用户操作时间时发生错误: {Username}, AccountId: {AccountId}", 
                    request.Username, request.AccountId);
                return StatusCode(500, new
                {
                    success = false,
                    message = "记录操作时间时发生内部错误",
                    data = (object?)null
                });
            }
        }

        /// <summary>
        /// 获取当前用户的坐席账号信息
        /// </summary>
        /// <returns>账号信息</returns>
        [HttpGet("current")]
        public async Task<IActionResult> GetCurrentAccount()
        {
            try
            {
                var username = User.FindFirst(ClaimTypes.Name)?.Value;
                if (string.IsNullOrEmpty(username))
                {
                    return Unauthorized(new
                    {
                        success = false,
                        message = "用户未登录",
                        data = (object?)null
                    });
                }

                var result = await _agentAccountService.GetUserCurrentAccountAsync(username);
                
                return Ok(new
                {
                    success = true,
                    message = result != null ? "获取账号信息成功" : "当前用户没有使用中的坐席账号",
                    data = result
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取当前用户坐席账号时发生错误");
                return StatusCode(500, new
                {
                    success = false,
                    message = "获取账号信息时发生内部错误",
                    data = (object?)null
                });
            }
        }

        /// <summary>
        /// 获取指定用户的坐席账号信息
        /// </summary>
        /// <param name="username">用户名</param>
        /// <returns>账号信息</returns>
        [HttpGet("user/{username}")]
        public async Task<IActionResult> GetUserAccount(string username)
        {
            try
            {
                if (string.IsNullOrEmpty(username))
                {
                    return BadRequest(new
                    {
                        success = false,
                        message = "用户名不能为空",
                        data = (object?)null
                    });
                }

                var result = await _agentAccountService.GetUserCurrentAccountAsync(username);
                
                return Ok(new
                {
                    success = true,
                    message = result != null ? "获取账号信息成功" : "该用户没有使用中的坐席账号",
                    data = result
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取用户坐席账号时发生错误: {Username}", username);
                return StatusCode(500, new
                {
                    success = false,
                    message = "获取账号信息时发生内部错误",
                    data = (object?)null
                });
            }
        }

        /// <summary>
        /// 获取所有坐席账号列表（管理员功能）
        /// </summary>
        /// <returns>账号列表</returns>
        [HttpGet("all")]
        [Authorize(Roles = "Admin,SuperAdmin")]
        public async Task<IActionResult> GetAllAccounts()
        {
            try
            {
                var result = await _agentAccountService.GetAllAccountsAsync();
                
                return Ok(new
                {
                    success = true,
                    message = "获取坐席账号列表成功",
                    data = result
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取所有坐席账号列表时发生错误");
                return StatusCode(500, new
                {
                    success = false,
                    message = "获取账号列表时发生内部错误",
                    data = (object?)null
                });
            }
        }

        /// <summary>
        /// 手动清理过期的坐席账号权限（管理员功能）
        /// </summary>
        /// <returns>清理结果</returns>
        [HttpPost("cleanup")]
        //[Authorize(Roles = "Admin,SuperAdmin")]
        [Authorize]
        public async Task<IActionResult> CleanupExpiredAccounts()
        {
            try
            {
                var result = await _agentAccountService.CleanupExpiredAccountsAsync();
                
                return Ok(new
                {
                    success = true,
                    message = $"成功清理了 {result} 个过期的坐席账号权限",
                    data = new { cleanedCount = result }
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "手动清理过期坐席账号权限时发生错误");
                return StatusCode(500, new
                {
                    success = false,
                    message = "清理过期账号权限时发生内部错误",
                    data = (object?)null
                });
            }
        }

        /// <summary>
        /// 清理未使用坐席账号的手机号（管理员功能）
        /// </summary>
        /// <returns>清理结果</returns>
        [HttpPost("cleanup-phone")]
        [Authorize]
        public async Task<IActionResult> CleanupAccountsPhone()
        {
            try
            {
                var result = await _agentAccountService.CleanupAccountsPhoneAsync();
                
                return Ok(new
                {
                    success = true,
                    message = $"成功清理了 {result} 个坐席账号的手机号",
                    data = new { cleanedCount = result }
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "清理坐席账号手机号时发生错误");
                return StatusCode(500, new
                {
                    success = false,
                    message = "清理坐席账号手机号时发生内部错误",
                    data = (object?)null
                });
            }
        }

        /// <summary>
        /// 获取坐席使用状态统计
        /// </summary>
        /// <returns>坐席使用状态统计信息</returns>
        [HttpGet("status")]
        public async Task<IActionResult> GetAccountStatus()
        {
            try
            {
                var result = await _agentAccountService.GetAccountStatusAsync();
                
                return Ok(new
                {
                    success = true,
                    message = "获取坐席使用状态统计成功",
                    data = result
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取坐席使用状态统计时发生错误");
                return StatusCode(500, new
                {
                    success = false,
                    message = "获取坐席使用状态统计时发生内部错误",
                    data = (object?)null
                });
            }
        }

        /// <summary>
        /// 获取指定用户的坐席申请状态
        /// </summary>
        /// <param name="request">用户坐席状态查询请求</param>
        /// <returns>用户坐席状态信息</returns>
        [HttpPost("user-status")]
        public async Task<IActionResult> GetUserAgentStatus([FromBody] UserAgentStatusRequest request)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }

                if (string.IsNullOrEmpty(request.Username))
                {
                    return BadRequest(new
                    {
                        success = false,
                        message = "用户名不能为空",
                        data = (object?)null
                    });
                }

                var result = await _agentAccountService.GetUserAgentStatusAsync(request.Username);
                
                return Ok(new
                {
                    success = true,
                    message = "获取用户坐席状态成功",
                    data = result
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取用户坐席状态时发生错误");
                return StatusCode(500, new
                {
                    success = false,
                    message = "获取用户坐席状态时发生内部错误",
                    data = (object?)null
                });
            }
        }
    }
}